package com.fast.fastenjoy.base.verify.mapping;

import java.io.Serializable;

import com.alibaba.fastjson.JSONObject;
import com.fast.fastenjoy.base.domain.BaseDomain;
import com.fast.fastenjoy.base.manager.EntityManager;
import com.fast.fastenjoy.base.utils.BeanExUtils;
import com.fast.fastenjoy.base.verify.exception.VerifyException;

/**
 * 验证对象
 * 
 * <b>修改历史:</b> <br/>
 *  version 1.0.0 2014-6-4 Ckuble Initial Version <br/>
 * @param <T>
 */
public class VerifyObject {

	private Object obj;
	
	private EntityManager<?> entityManager;
	
	private VerifyMapping verifyMapping;
	
	public static VerifyObject build(Object obj, EntityManager<?> entityManager){
		
		if(obj == null || entityManager == null){
			return null;
		}
		
		VerifyMapping verifyMapping = VerifyMapping.build(obj.getClass());
		
		if(verifyMapping == null || verifyMapping.getVerifyFields().isEmpty()){
			return null;
		}
		
		VerifyObject vo = new VerifyObject(obj, entityManager);
		vo.verifyMapping = verifyMapping;
		
		return vo;
	}
	
	private VerifyObject(Object obj, EntityManager<?> entityManager){
		this.obj = obj;
		this.entityManager = entityManager;
	}
	
	public void verify() throws VerifyException{
		verifyMapping.verify(this);
	}
	
	public Serializable getId(){
		
		return BaseDomain.getId(obj, BaseDomain.FIELD_ID);
	}
	
	public Object getFieldValue(String fieldName){
		
		Object value = null;
		
		try {
			value = BeanExUtils.getPropertyValue(obj, fieldName);
		} catch (Throwable e) {
		}
		
		return value;
	}
	
	public String getFieldStringValue(String fieldName){
		
		Object fieldValue = getFieldValue(fieldName);
		
		return fieldValue == null ? null : String.valueOf(fieldValue);
	}
	
	public EntityManager<?> getEntityManager(){
		
		return entityManager;
	}
	
	@Override
	public String toString() {
		return JSONObject.toJSONString(this);
	}
}
